#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include "Mutex.hpp"
#include "Log.hpp"

using namespace LogModule;
using namespace MutexModule;

const int defaultfd = -1;

class UdpServer
{
public:
    UdpServer(uint16_t port, std::string &ip)
        : _sockfd(defaultfd), _port(port), _ip(ip)
    {
    }

    void Init()
    {
        // 1.创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::Fatal) << "socket error";
            exit(1);
        }
        LOG(LogLevel::Info) << "socket created success";

        // 2.绑定socket信息，包括IP地址和端口号
        // 2.1 填充socketaddr_in结构体
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        //我会不会把ip和port发送给对方？会
        //所以，IP信息和端口号一定要发送到网络！
        //本地格式->网络序列
        local.sin_port = htons(_port);
        //Ip也是如此，//1.把ip转成uint32_t 2.把uint32_t转成网络序列 ->in_addr_t inet_addr(const char* cp)
        local.sin_addr.s_addr =inet_addr(_ip.c_str());

        int n=bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
    }

    void Start()
    {
    }

    ~UdpServer()
    {
    }

private:
    int _sockfd;
    uint16_t _port;
    std::string _ip;//用的是字符串风格的IP地址，点分十进制
};
